package com.klod.api

import com.klod.data.bean.BannerDetailBean
import com.klod.data.bean.BaseResponseBean

import com.klod.data.services.HomeServices
import com.klod.ext.responseFail
import com.klod.ext.responseSuccess
import io.ktor.http.*
import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.java.KoinJavaComponent.inject

fun Application.configureHomeApi() {

    // Lazy inject
    val homeService by inject<HomeServices>(HomeServices::class.java)

    routing() {
        route("/home") {
            // 首页轮播图
            get("/BannerList") {
//                val header = call.request.header("MyCustomHeader")
//                println(header)

                call.respond(
                        homeService.getBanners().responseSuccess()
                )

            }
            get("/BannerList/{bId}") {
                call.respond(

                        homeService.getBanner(call.parameters["bId"]?.toInt() ?: -1).responseSuccess()

                )
//                    call.respondText("BannerList()")
            }
            post("addBanner") {
                try {
                    call.respond(
                        homeService.addBanner(call.receive<BannerDetailBean>()).responseSuccess()
                    )
                } catch (ex: IllegalStateException) {
                    call.respond(HttpStatusCode.BadRequest.description.responseFail())
                } catch (ex: JsonConvertException) {
                    call.respond(HttpStatusCode.BadRequest.description.responseFail())
                }
            }
            delete("deleteBanner") {
                val bId = call.receiveParameters()["bId"]?.toInt() ?: -1
                if (bId == -1) {
                    call.respond(BaseResponseBean.fail("Banner ID 错误"))
                    return@delete
                }
                if (homeService.deleteBanner(bId)) {
                    call.respond(null.responseSuccess())
                } else {
                    call.respond("没找到对应Id".responseFail())
                }

            }


        }

    }


}